package virtualstock.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import virtualstock.exception.GameNotFoundException;
import virtualstock.exception.InvalidParameterException;
import virtualstock.exception.PlayerNotFoundException;
import virtualstock.request.PortfolioController;
import virtualstock.util.PortfolioDetails;

/**
 * Servlet implementation class CreatePortfolioServlet
 */
public class CreatePortfolioServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private PortfolioController portfolioController;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreatePortfolioServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	PrintWriter out = response.getWriter();
    	
    	Long gameID = new Long((String) request.getParameter("gameid"));
    	Long playerID = new Long((String) request.getParameter("playerid"));
    	BigDecimal balance = new BigDecimal((String) request.getParameter("balance"));
    	out.print(gameID + "<br>");
    	out.print(playerID + "<br>");
    	out.print(balance + "<br>");
    	
    	try {
    		PortfolioDetails details = new PortfolioDetails(gameID, playerID, balance);
    		Long portfolioID = portfolioController.createPortfolio(details);
        	details.setPortfolioID(portfolioID);
		} catch (InvalidParameterException e) {
			out.print("InvalidParameterException");
			e.printStackTrace();
		} catch (GameNotFoundException e) {
			out.print("GameNotFoundException");
			e.printStackTrace();
		} catch (PlayerNotFoundException e) {
			out.print("PlayerNotFoundException");
			e.printStackTrace();
		}
		
		out.print("here");
		//request.getRequestDispatcher("ListPortfolioServlet").forward(request, response);
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
